package com.spring.housing1.server;

import cn.hutool.core.lang.UUID;
import com.spring.housing1.deliver.PitureEnhance;
import com.spring.housing1.pojo.FileUploadWithCards;
import com.spring.housing1.returnType.CommenResult;
import com.spring.housing1.pojo.DoctorInfo;
import com.spring.housing1.pojo.RoomInfo;
import com.spring.housing1.util.AsyncBussCenterCore;
import com.spring.housing1.other.FileUpload;
import com.spring.housing1.util.MapUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UpdateServer {

    // 访问图片时的基础url
    @Value("${FTP.URL}")
    private String baseUrl;

    // 文件在服务器端保存的主目录
    @Value("${FTP.BASEPATH}")
    private String basePath;
    // 文件在服务器端保存的主目录
    @Value("${FTP.returnUrl}")
    private String address;

    @Qualifier("Db1Template")
    @Autowired
    JdbcTemplate jdbcTemplate;

    /*
     * 异步对象
     * */
    @Autowired
    AsyncBussCenterCore asyncBussCenterCore;


    @Value("picture.filepath")
    String filePath;

    public CommenResult upadte(DoctorInfo param) {

        String sql = "update web_mana_user set user_name = ? ,real_name = ?,cell_phone =?,enable =?,room_id =?,update_at =?,pass_word =? where 1=1";
        sql += (" and id = " + param.getId());
        List arr = new ArrayList();
        param.setUpdate_at(new Date());
        arr.add(param.getUser_name());
        arr.add(param.getReal_name());
        arr.add(param.getCell_phone());

        arr.add(param.getEnable());
        arr.add(param.getRoom_id());
        arr.add(param.getUpdate_at());
        arr.add(param.getPass_word());
        int update = jdbcTemplate.update(sql, arr.toArray());
        return new CommenResult(200, "更新成功！", "~");
    }


    public CommenResult updateRoom(RoomInfo param) {

        String sql = "update room set room = ? ,descs = ?,enable =?   where 1=1";
        sql += (" and room_id = " + param.getRoom_id());
        List arr = new ArrayList();
        arr.add(param.getRoom());
        arr.add(param.getDescs());
        arr.add(param.getEnable());
        int update = jdbcTemplate.update(sql, arr.toArray());
        return new CommenResult(200, "更新成功！", "~");

    }

    public CommenResult insertRoom(RoomInfo param) {
        String sql = "insert into room(room,descs,enable,create_at) values(?,?,?,?)";
        param.setCreate_at(new Date());
        List arr = new ArrayList();
        arr.add(param.getRoom());
        arr.add(param.getDescs());
        arr.add(param.getEnable());
        arr.add(param.getCreate_at());
        int update = jdbcTemplate.update(sql, arr.toArray());
        return new CommenResult(200, "新增成功！", "~");

    }

    public CommenResult insertUsers(DoctorInfo param) {
        Function<DoctorInfo, List> functionArr = s -> {
            List arr = new ArrayList();
            s.setCreate_at(new Date());
            arr.add(s.getUser_name());
            arr.add(s.getReal_name());
            arr.add(s.getCell_phone());
            arr.add(s.getEnable());
            arr.add(s.getRoom_id());
            arr.add(s.getCreate_at());
            arr.add(s.getPass_word());
            arr.add(s.getName());
            return arr;
        };
        Function<List, Integer> functionCommom = s -> {
            String sql = "insert into  web_mana_user(user_name,real_name,cell_phone,enable,room_id,create_at,pass_word,name) values (?,?,?,?,?,?,?,?)";
            int update = jdbcTemplate.update(sql, s.toArray());
            return update;
        };
        Integer apply = functionArr.andThen(functionCommom).apply(param);
        return new CommenResult(200, "新增成功！", "~");
    }

    public CommenResult uploadFile(FileUploadWithCards fileUploadWithCards) {
////       上传文件
//        asyncBussCenterCore.asyncDeal(() -> {
//            try {
//                FileUpload.upload(fileUploadWithCards.getFile(),filePath,fileUploadWithCards.getFileName());
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        });
        return null;
    }

    public synchronized CommenResult fileUpload(MultipartFile[] fileUploadWithCards, String param, String param2, String param3) {
        synchronized (this) {
            int i = 1;
            String filePaths = "";

            for (MultipartFile file : fileUploadWithCards) {
                try {
                    //调取外部接口获取图片对比度曾强后的io数据
                    InputStream image = PitureEnhance.getImage(file.getBytes());
                    //清晰度增强
                    InputStream image2 = PitureEnhance.getImage2(IOUtils.toByteArray(image));
                    //1、给上传的图片生成新的文件名
                    //1.1获取原始文件名
                    String oldName = file.getOriginalFilename();
//                    文件名为病单id+序列号
                    String newName = param + "_" + i + oldName.substring(oldName.lastIndexOf("."));
                    //1.3生成文件在服务器端存储的子目录(以患者id为路径)
                    String filePath = "/" + param3 + "/" + param + "/";

                    //3、把图片上传到图片服务器
                    //3.1获取上传的io流
                    InputStream input = file.getInputStream();
//                异步上传文件
                    asyncBussCenterCore.asyncDeal(() -> {
                        //3.2调用FtpUtil工具类进行上传
                        boolean result = FileUpload.uploadFile(filePath, newName, image2);
                    });
                    if (Objects.equals("", filePaths)) {
                        filePaths = address + filePath + newName;

                    } else {
                        filePaths += ";" + address + filePath + newName;
                    }
                } catch (Exception e) {
                    return new CommenResult(201, "图片上传失败！", "");
                }
                i++;
            }
            //修改订单状态
            jdbcTemplate.update("update ctp_aff set cd_result =?,enable = 2,view = 0  where  node_id =? and doctor_id =? ", param2, param, param3);
            List<String> collect = Arrays.stream(filePaths.split(";")).map(res -> {
                if (!res.equals("")) {
                    String ress = "http://" + res;
                    return ress;
                }
                return res;
            }).filter(res ->
                    !"".equals(res)
            ).collect(Collectors.toList());
            String s = "";
            for (int j = 0; j < collect.size(); j++) {
                if (j == 0) {
                    s += collect.get(j);
                } else {
                    s += ("," + collect.get(j));
                }
            }

            jdbcTemplate.update("update ctp_aff set img_path =?  where  node_id =? ", s, param);
            jdbcTemplate.update("update numbers set  enable = 0, times =? , open_id = ?,node_id =? ,front =? where node_id =? " ,null,null,null,null,param);


            return new CommenResult(200, "操作成功!", collect);
        }

    }

    public CommenResult updateNodeInfo(Map<String, String> node_id) {
//参数获取
        List list = MapUtils.mapKeyToList(node_id, "patient", "cell_phone", "doctor_id", "doctor2_id", "enable", "remark", "cd_result", "deal_result");
//获取值
        List list2 = MapUtils.mapToList(node_id, "patient", "cell_phone", "doctor_id", "doctor2_id", "enable", "remark", "cd_result", "deal_result");

//拼接sql
        Function<List, String> supplier = s -> {
            int i = 0;
            String sql = "update ctp_aff ";
            if (s.size() == 0) {
                return "";
            }
            for (int j = 0; j < s.size(); j++) {
                if (i == 0 && i != s.size() - 1) {
                    sql += (" set " + s.get(j) + " = ? , ");
                } else if (i == (s.size() - 1)) {
                    sql += (s.get(j) + " = ? ");
                } else {
                    sql += (s.get(j) + " = ? , ");
                }
                i++;
            }
            return sql;
        };
        String apply = supplier.apply(list);
//        没有任何更新则跳过
        if (apply.equals("")) {
            log.info(apply);
            return new CommenResult(200, "更新成功!", "~");
        }
        apply += "  where node_id = ?";
        list2.add(node_id.get("node_id"));
        int update = jdbcTemplate.update(apply, list2.toArray());
        log.info(apply);
        return new CommenResult(200, "更新成功!", "~");
    }

    public CommenResult delNodeInfo(Map<String,String > param) {
        jdbcTemplate.update("delete from  ctp_aff where node_id = ?",param.get("node_id"));
        return new CommenResult(200, "删除成功!", "~");
    }

    public CommenResult doctorHandle(Map<String, String> param) {
//        修改病单状态和处理结果
        jdbcTemplate.update("update ctp_aff set deal_result =?,enable = 1,view =0  where  node_id =? and doctor2_id =?  ", param.get("param2"), param.get("param"), param.get("param3"));
        return new CommenResult(200, "操作成功!", "~");
    }
}
